<?php

class CC_Helpdesk_RuleParser
{
    /**
     * @var CC\Entity\Ticket Ticket Entity
     */
    protected $_ticket;
    /**
     * @var CC\Entity\User User Entity
     */
    protected $_user;
    /**
     * @var CC_Helpdesk_ActionParser Action Parser
     */
    protected $_actionParser;
    
    /**
     * Constructor
     * 
     * @param CC_Helpdesk_ActionParser $actionParser
     * @param CC\Entity\Ticket $ticket Ticket to apply rules to
     * @param CC\Entity\User $user 
     */
    public function __construct(CC_Helpdesk_ActionParser $actionParser, CC\Entity\Ticket $ticket = null, CC\Entity\User $user = null)
    {
        $this->_actionParser = $actionParser;
        $this->_ticket = $ticket;
        $this->_user = $user;
    }
    
    /**
     * Ticket accessor
     * @return CC\Entity\Ticket
     */
    public function getTicket()
    {
        return $this->_ticket;
    }

    /**
     * User accessor
     * @return CC\Entity\User
     */
	public function getUser()
    {
        return $this->_user;
    }

    /**
     * Ticket mutator
     * @param CC\Entity\Ticket $ticket
     */
	public function setTicket($ticket)
    {
        $this->_ticket = $ticket;
    }

    /**
     * User mutator
     * @param CC\Entity\User $user
     */
	public function setUser($user)
    {
        $this->_user = $user;
    }

    /**
     * Get all rules for the user and try apply it to the ticket
     */
	public function parse()
    {
        // @TODO: check for valid ticket and user
        if($this->_ticket === null || !($this->_ticket instanceof CC\Entity\Ticket))
            throw new Zend_Exception('Please supply a valid ticket object');
        
        if($this->_user === null || !($this->_user instanceof CC\Entity\User))
            throw new Zend_Exception('Please supply a valid user object');
        
        $rules = $this->_user->getTicketRules();
        
        if($rules)
        {
            foreach($rules as $rule)
            {
                $ruleParams = CC_Inflector::parseParamString($rule->getRuleExpression());
                // Create an instance of the desired rule
                // @TODO: Check if instance of Rule Abstract class
                //$ruleClass = $rule->getRuleObject();
                $ruleClass = $ruleParams['action'];
                $ruleObj = new $ruleClass();
                $ruleObj->setTicket($this->_ticket)
                        ->setRuleExpression($rule->getRuleExpression());
                
                // Parse the ticket
                $ruleRes = $ruleObj->parse();
                
                // Parse rule actions then finish.
                if($ruleRes)
                {
                    $this->_actionParser
                         ->setActionExpression($rule->getRuleAction())
                         ->setTicket($this->_ticket)
                         ->parse();
                    break;
                }
            }
        }
    }
}
?>